<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    label-width="150px"
                    :rules="formDataRules"
                    ref="formDataRef"
                >
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="结算编号">
                                {{ formData.billNo }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="单据机构">
                                {{ formData.orgName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="结算类型" prop="businessType">
                                <el-select
                                    v-model="formData.businessType"
                                    placeholder="请选择"
                                    v-if="!isRedSingle"
                                >
                                    <el-option
                                        v-for="item in businessTypeList"
                                        :key="item.value"
                                        :label="item.key"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                                <span v-else>{{ businessType }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="源单编号">
                                <span>
                                    {{ formData.sourceBillNo }}
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="sourceBillNoClick"
                                        v-if="formData.sourceBillNo"
                                    ></i>
                                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item
                                label="结算单位"
                                prop="settlementUnitName"
                            >
                                <span>{{ formData.settlementUnitName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="结算日期"
                                prop="settlementDate"
                            >
                                <el-date-picker
                                    v-model="formData.settlementDate"
                                    type="date"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd"
                                    :clearable="false"
                                    v-if="!isRedSingle"
                                >
                                </el-date-picker>
                                <span v-else>{{
                                    formData.settlementDate
                                }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="结算金额(元)" prop="amount">
                                {{ formData.amount }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="验收人员">
                                <el-input
                                    v-model="formData.acceptancePersonnelName"
                                    readonly
                                    v-if="!isRedSingle"
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="acceptancePersonnelNameClick"
                                    ></i>
                                </el-input>
                                <span v-else>{{
                                    formData.acceptancePersonnelName
                                }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="发票编号">
                                <el-input
                                    placeholder="请填写发票编号"
                                    v-model="formData.invoiceNo"
                                    v-enterInteger1
                                    v-if="!isRedSingle"
                                ></el-input>
                                <span v-else>{{ formData.invoiceNo }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="服务费用(含税,元)">
                                {{ formData.freight }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="税率%" prop="taxRate">
                                <span>{{ formData.taxRate }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="税价合计">
                                {{ formData.totalAmount }} 元
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="税额" prop="taxAmount">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.taxAmount"
                                    v-enter-float="{
                                        set: formData,
                                        key: 'taxAmount'
                                    }"
                                    v-if="!isRedSingle"
                                ></el-input>
                                <span v-else>{{ formData.taxAmount }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="税额差额">
                                {{ formData.taxDifference }} 元
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="币种" prop="currency">
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="本位币" prop="baseCurName">
                                {{ formData.baseCurName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="传财务共享">
                                {{ formData.easId ? '已传' : '未传'}}
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="本位币汇率" prop="baseCurRate">
                                <span>{{ formData.baseCurRate }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-form-item label="备注">
                            <el-input
                                type="textarea"
                                :rows="2"
                                resize="none"
                                placeholder="请输入内容"
                                v-model="formData.remarks"
                                maxlength='500'
                            >
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                {{ showState(formData.state) }}
                                <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="冲红单"
                                ><span :style="redBillStateStyle">{{
                                    redBillStateFun
                                }}</span></el-form-item
                            >
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button type="primary" style="background: #2e61d7" @click="save"
                >保存</el-button
            >

            <el-button @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState, mapMutations } from 'vuex'
import {
    formatDate,
    showLoading,
    hideLoading,
    openAppClient
} from '@/utils/common'
import priceSetRequest from '@/api/materialSettlement/priceSettlement'
import request from '@/api/materials/materialAcceptance'

export default {
    data () {
        return {
            //表单数据
            formData: {
                acceptancePersonnelId: '',
                acceptancePersonnelName: '',
                amount: '',
                baseCurAmount: 0,
                baseCurFreight: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: '',
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                billNo: '',
                businessType: 0,
                currency: '',
                currencyId: '',
                easId: '',
                evaluationLevel: '',
                founderId: '',
                founderName: '',
                freight: '',
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                redBillId: '',
                redBillNo: '',
                redBillState: null,
                remarks: '',
                rmbAmount: 0,
                rmbFreight: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settlementDate: formatDate(new Date(), 'yyyy-MM-dd'),
                settlementUnitId: '',
                settlementUnitName: '',
                sourceBillId: '',
                sourceBillNo: '',
                sourceId: '',
                sourceNumber: '',
                state: 0,
                taxAmount: '',
                taxDifference: '',
                taxRate: '',
                totalAmount: '',
                workId: ''
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            businessTypeList: [
                {
                    value: 0,
                    key: '零星采购计划'
                },
                {
                    value: 1,
                    key: '物资采购合同'
                },
                {
                    value: 2,
                    key: '调入（调拨单）'
                }
            ],
            formDataRules: {
                businessType: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'blur'
                    }
                ],
                // taxRate: [
                //     { required: true, message: '请输入税率', trigger: 'blur' }
                // ],
                taxAmount: [
                    { required: true, message: '请输入税额', trigger: 'blur' }
                ],
                // currencyId: [
                //     { required: true, message: '请选择币种', trigger: 'blur' }
                // ],
                invoiceNo: [
                    {
                        required: true,
                        message: '请填写发票号',
                        trigger: 'blur'
                    }
                ]
                // baseCurName: [
                //     {
                //         required: true,
                //         message: '请选择本位币',
                //         trigger: 'blur'
                //     }
                // ],
                // baseCurRate: [
                //     {
                //         required: true,
                //         message: '请填写本位币汇率',
                //         trigger: 'blur'
                //     }
                // ]
            },
            isRedSingle: false,
            redFormData: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            isBaseCurRate: true,
            billid: '',
            businessType: ''
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },

        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        'formData.isAccepSettle' () {
            // 如果验结一体未勾选,则需要清除发票号的提示信息
            if (!this.formData.isAccepSettle) {
                this.$refs.formDataRef.clearValidate('invoiceNo')
                this.formData.invoiceNo = ''
            }
        },
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' () {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                this.formData.baseCurRate = null
            }
        },
        // // 监听验收金额
        // 'formData.amount' () {
        //     // 税价合计 = 验收金额 + 税额
        //     this.formData.totalAmount =
        //         +this.formData.amount + +this.formData.taxAmount
        //     // 验收金额(本位币) = 验收金额 * 本位币汇率
        //     this.formData.baseCurAcceptanceAmount =
        //         +this.formData.amount * +this.formData.baseCurRate
        // },
        // // 监听税额
        // 'formData.taxAmount' () {
        //     // 税价合计 = 验收金额+税额
        //     this.formData.totalAmount =
        //         +this.formData.amount + +this.formData.taxAmount
        // },
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    components: {},
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.formData.orgName = this.orgName
        // this.formData.purchaserName = localStorage.getItem('userName')
        this.formData.acceptancePersonnelName =
            localStorage.getItem('userName')
        const { baseCyByOrgId } = this.userInfo
        // this.formData.baseCurName = baseCyByOrgId.currencyName //本位币
        this.formData.baseCurId = baseCyByOrgId.currency
        this.$route.query.isRedSingle === '1'
            ? (this.isRedSingle = true)
            : (this.isRedSingle = false)
        if (this.$route.query.isRedSingle === '1') {
            this.getRedList()
        }
        this.billid = this.$route.query.billid
    },
    mounted () {},
    beforeDestroy () {},
    methods: {
        ...mapMutations(['setSelectedInfo']),
        // 如果是点击冲红单进入的新增页,则需要返显数据,只有备注能修改,其余均不能修改
        async getRedList () {
            showLoading()
            try {
                let data = await priceSetRequest.redSingle(
                    this.$route.query.billid
                )
                this.redFormData = this._.cloneDeep(data)
                this.businessType = this.businessTypeList.find(
                    item => item.value === data.businessType
                ).key
                data.currency = this.currencyForm.find(
                    x => x.value === data.currencyId
                ).label

                this.formData = data
            } finally {
                hideLoading()
            }
        },
        // 源单编号
        sourceBillNoClick () {
            let url = ''
            let name = ''
            switch (this.formData.businessType) {
            case 0:
                url = '/sporadicPurchaseParticulars'
                name = '查看零星采购计划'
                break
            case 1:
                url = '/ctMaterialApplyShow'
                name = '查看物资采购合同'
                break
            case 2:
                url = '/revolveAllocationShow'
                name = '查看调入(调拨单)'
                break
            }
            openAppClient(
                `${url}?billid=${this.formData.sourceBillId}&isview=${true}`,
                `${name}`
            )
        },
        // 选择验收人员
        async acceptancePersonnelNameClick () {
            let data = await request.getAcceptancerName()
            this.formData.acceptancePersonnelId = data.userId
            this.formData.acceptancePersonnelName = data.userName
        },

        //保存按钮
        save () {
            this.$refs.formDataRef.validate(valid => {
                if (!valid) return false
                if (this.isRedSingle) {
                    this.redFormData.remarks = this.formData.remarks
                }
                priceSetRequest
                    .basicInfoAdd(
                        this.isRedSingle ? this.redFormData : this.formData
                    )
                    .then(res => {
                        this.clientPop(
                            'info',
                            '保存成功,是否继续',
                            () => {
                                this.$router.replace({
                                    path: '/priceSettlementEdit',
                                    query: {
                                        billid: res,
                                        name: 'settlement'
                                    }
                                })
                            },
                            null,
                            this.handleClose
                        )
                    })
            })
        },
        //取消按钮
        handleClose () {
            this.$router.replace('/priceSettlementList')
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
</style>
